package com.sxf.rental.utils;

import com.sxf.rental.entity.Permission;
import com.sxf.rental.vo.RouteVo;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class RouteTreeUtils {
    public static List<RouteVo> buildRouteTree(List<Permission> permissionList,int pid){
        List<RouteVo> routeVoList=new ArrayList<>();
        Optional.ofNullable(permissionList).orElse(new ArrayList<>())
                .stream().filter(permission -> permission!=null && permission.getPid()==pid)
                        .forEach(permission -> {
                            RouteVo routeVo=new RouteVo();
                            routeVo.setPath(permission.getRoutePath());
                            routeVo.setName(permission.getRouteName());
                            //是否根路径
                            if (permission.getPid()==0){
                                routeVo.setComponent("Layout");
                                routeVo.setAlwaysShow(true);
                            }else {
                                routeVo.setComponent(permission.getRouteUrl());
                                routeVo.setAlwaysShow(false);
                            }
                            routeVo.setMeta(routeVo.new Meta(permission.getPermissionLabel(),
                                    permission.getIcon(),permission.getPermissionCode().split(",")));
                            List<RouteVo> children=buildRouteTree(permissionList,permission.getId());
                            routeVo.setChildren(children);
                            routeVoList.add(routeVo);
                        });
        return routeVoList;
    }

    public static List<Permission> buildMenuTree(List<Permission> permissionList,int pid){
        List<Permission> menuList=new ArrayList<>();
        Optional.ofNullable(permissionList).orElse(new ArrayList<>())
                .stream().filter(permission -> permission!=null && permission.getPid()==pid)
                        .forEach(permission -> {
                            Permission menu=new Permission();
                            BeanUtils.copyProperties(permission,menu);
                            menu.setChildren(buildMenuTree(permissionList,permission.getId()));
                            menuList.add(menu);
                            /*
                            //新建一个Permission menu=new Permission();对象进行操作的原因是，保留permissionList中的原始数据，
                            //如果直接操作permissionList，会导致permissionList中的数据被修改，
                            //如果有其他方法或者在多线程的情况下，需要这个permissionList中的原始数据，就会造成不便
                            permission.setChildren(buildMenuTree(permissionList,permission.getId()));
                            menuList.add(permission);
                            */
                        });
        return menuList;


    }
}
